package command
{
	import business.BabyDelegate;
	
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import event.SaveBabyEvent;
	
	import model.BabyChartModelLocator;
	
	import mx.containers.TitleWindow;
	import mx.controls.Alert;
	import mx.managers.PopUpManager;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	import view.SaveDataPopup;
	
	import vo.Baby;

	public class SaveBabyCommand implements IResponder, ICommand
	{
		private var babyChartModel:BabyChartModelLocator = BabyChartModelLocator.getInstance();
		private var titleWindow:TitleWindow;
		
		public function result(data:Object):void
		{
			var resultEvent:ResultEvent = ResultEvent(data);
			var xml:XML = XML(resultEvent.message.body);
			if (xml.failed > 0) {
				if (xml.failed == 2) {
					(SaveDataPopup(titleWindow)).note.text = "This baby already exists with the same name, dob and password. Change one and try again.";
				} else {
					(SaveDataPopup(titleWindow)).note.text = "Saving baby failed. Please try again.";
				}
				(SaveDataPopup(titleWindow)).note.setStyle("color", "#ff0000"); 
			} else {
				Alert.show("Baby data saved successfully!");
				PopUpManager.removePopUp(titleWindow);
				var baby:Baby = new Baby(xml);
				babyChartModel.baby = baby;
			}
		}
		
		public function fault(info:Object):void
		{
		}
		
		public function execute(event:CairngormEvent):void
		{
			var realEvent:SaveBabyEvent = SaveBabyEvent(event);
			titleWindow = realEvent.titleWindow;
			new BabyDelegate(this).saveBabyData(realEvent.newps);
		}
		
	}
}